package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter(
        urlPatterns = {"/manage/*"},
        servletNames = {"servlet.CompanyAddServlet",
                "servlet.CompanyServlet",
                "servlet.ResumeServlet",
                "servlet.UserAddServlet",
                "servlet.UserServlet"},
        initParams = {@WebInitParam(name = "loginPage", value = "login.jsp")})

public class AuthorityFilter implements Filter {
    private String loginPage;


    public void init(FilterConfig filterConfig) throws ServletException {
        loginPage = filterConfig.getInitParameter("loginPage");
        if (null == loginPage) {
            loginPage = "login.jsp";
        }

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        if ("/UserServlet".equals(req.getServletPath()) &&
                "type=login".equals(req.getQueryString())) {
            chain.doFilter(request, response);
            return;
        }
        if (session.getAttribute("SESSION_USER") == null) {
            resp.sendRedirect(req.getContextPath() + "/" + loginPage);
        } else {
            chain.doFilter(request, response);
        }
    }

    public void destroy() {

    }
}
